package com.jpa.element.collection.mapping.tutorial.service;

import com.jpa.element.collection.mapping.tutorial.domain.Address;
import com.jpa.element.collection.mapping.tutorial.domain.Label;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import java.util.List;

public class LabelService {

    private EntityManager em;

    public LabelService(EntityManager em) {
        this.em = em;
    }

    public Label createLabel(int id, String name, List<Address> addresses) {
        Label label = new Label(id, name, addresses);
        em.persist(label);

        return label;
    }

    public void removeLabel(int id) {
        Label label = em.find(Label.class, id);

        if (label != null) {
            em.remove(label);
        }
    }

    public Label changeLabelName(int id, String name) {
        Label label = em.find(Label.class, id);

        if (label != null) {
            label.setName(name);
        }

        return label;
    }

    public Label findLabel(int id) {
        return em.find(Label.class, id);
    }

    public List<Label> findAllLabels() {
        TypedQuery<Label> query = em.createQuery("SELECT l FROM Label l", Label.class);
        return query.getResultList();
    }
}
